import java.util.ArrayList;
import java.util.List;

public class WeatherData implements IObservable {

    private float temperature;
    private float humidity;
    private float pressure;
    private boolean changed = false;
    private List<Observer> observers;

    public WeatherData() {
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers(Object arg) {
        if (changed) {
            for (Observer o : observers) {
                o.update(this, arg);
            }
            changed = false;
        }
    }

    @Override
    public void notifyObservers() {
        notifyObservers(null);
    }

    public void measurementChanged() {
        // 要求观察者自己拉取数据
        // notifyObservers();
        // 主动推送数据
        Data data = new Data();
        data.setTemperature(temperature);
        data.setHumidity(humidity);
        data.setPressure(pressure);
        notifyObservers(data);
    }

    /**
     * 3个参数实际上应该是从服务器或检测器获取的数据
     */
    public void setMeasurements(float temperature, float humidity, float pressure) {
        /**
         * 偏差超过0.5 才真正向观察者更新一次数据
         */
        if (Math.abs(temperature-this.temperature)>=0.5 || Math.abs(humidity-this.humidity)>=0.5 || Math.abs(pressure-this.pressure)>=0.5) {
            changed = true;
            this.temperature = temperature;
            this.humidity = humidity;
            this.pressure = pressure;
            measurementChanged();
        }
    }

    public float getTemperature() { return temperature; }

    public float getHumidity() {
        return humidity;
    }

    public float getPressure() {
        return pressure;
    }
}
